﻿using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Day.Data;
using DynamicData;
using Microsoft.EntityFrameworkCore;

namespace MemorialDay.App.ViewModels;

public class MainViewModel : ViewModelBase
{

    #region Vis

    private bool _initVisible = true;
    public bool InitVisible
    {
        get => _initVisible;
        set => SetField(ref _initVisible, value);
    }

    private bool _addVisible;
    public bool AddVisible
    {
        get => _addVisible;
        set
        {
            SetField(ref _addVisible, value);
            InitVisible = !value;
        }
    }
    
    private bool _detailedVisible;
    public bool DetailedVisible
    {
        get => _detailedVisible;
        set
        {
            SetField(ref _detailedVisible, value);
            InitVisible = !value;
        }
    }

    #endregion
    
    public DayModel ThisDay { get; set; }

    private DayContext Context { get; set; }
    public ObservableCollection<DayModel> DayList { get; set; }

    public async void Add(DayModel model)
    {
        await Context.Days.AddAsync(model);
        await Context.SaveChangesAsync();
        DayList.Add(model);
    }

    public async Task<bool> Change(DayModel dayModel)
    {
        var target = await Context.Days.FirstOrDefaultAsync(x => x.Key == dayModel.Key);
        if (target == null) return false;
        target.DayName = dayModel.DayName;
        target.DayIntroduce = dayModel.DayIntroduce;
        target.DayImage = dayModel.DayImage;
        target.DayTime = dayModel.DayTime;
        await Context.SaveChangesAsync();
        return true;
    }

    public MainViewModel()
    {
        Context = new DayContext();
        DayList = new ObservableCollection<DayModel>(Context.Days);
        ThisDay = DayList.FirstOrDefault() ?? DayStatic.DefaultDay;
    }
}